package com.java.cfpaying.controller;


import com.alibaba.fastjson.JSONObject;
import com.java.cfpaying.entity.User;
import com.java.cfpaying.feign.FeignInterface;
import com.java.cfpaying.service.UserService;
import com.java.jwt.filter.utils.utils.RequestHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;

import javax.xml.bind.DatatypeConverter;
import java.nio.charset.StandardCharsets;

/**
 * @author cf
 * @date 2021/7/7 16:10
 */
@RestController
@RequestMapping("/user1")
public class UserController {

    @Autowired
    private FeignInterface feignInterface;

    @Autowired
    private UserService userService;


    @GetMapping("/getCurrentUser")
    @PreAuthorize("hasAuthority('cf:admin')")
    public JSONObject getCurrentUser(Authentication authentication) {
        JSONObject data = new JSONObject();
        data.put("enhance", RequestHolder.get("enhance"));
        data.put("username", RequestHolder.get("username"));
        data.put("password", RequestHolder.get("password"));
        data.put("Authorities", RequestHolder.get("Authorities"));
        return data;
    }


    @PostMapping("/getJwt")
    public Object getJwt(
            @RequestParam("grant_type") String grantType,
            @RequestParam("username") String username,
            @RequestParam("password") String password,
            @RequestParam(value = "scope", required = false) String scope
    ) throws Exception {
        String encoding = DatatypeConverter.printBase64Binary(("admin:admin").getBytes(StandardCharsets.UTF_8));
        return feignInterface.getToken("Basic ".concat(encoding), grantType, username, password, scope);
    }


    @PostMapping("/getUser")
    public User getUser() {
        return userService.getById(1);
    }


}
